package com.github.xjjdog.optimisticlock;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Fork(2)
@State(Scope.Benchmark)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.Throughput)
public class AtomicSynclBenchmark {
    int i = 0;
    AtomicInteger atomicInteger = new AtomicInteger(0);

    @Benchmark
    @Threads(20)
    public void atomic() {
        atomicInteger.getAndIncrement();
    }

    @Benchmark
    @Threads(20)
    public void sync() {
        synchronized (this) {
            i++;
        }
    }

    public static void main(String[] args) throws Exception {
        Options opts = new OptionsBuilder()
                .include(AtomicSynclBenchmark.class.getSimpleName())
                .resultFormat(ResultFormatType.CSV)
                .build();

        new Runner(opts).run();
    }
}
